import Vue from 'vue'
import Vuex from 'vuex'
import service from '@/api/index'
import details from './details.js'
import jump from './jump.js'
import { notice, success } from '../utils/res.js'

Vue.use(Vuex)

const state = {
  token: JSON.parse(window.sessionStorage.getItem('TOKEN') || window.localStorage.getItem('LOCALTOKEN') || '{ "access_token": "" }'),
  user: JSON.parse(window.sessionStorage.getItem('USER') || '{ "id": "", "current_win_codes": "" }'),
  aroundId: JSON.parse(window.sessionStorage.getItem('AROUNID')|| '{"aroundId":""}'),
  roomId: JSON.parse(window.sessionStorage.getItem('ROOMID')|| '{"roomId":""}')
}

const actions = {
  async getUser ({ commit }, data) {
    const res = await service.getUser(data)
    if (res.RET === 1) commit('USER', res.DATA)
    else notice(res.MSG)
    return res
  },
  async register ({ commit }, data) {
    const res = await service.register(data)
    if (res.RET === 1) commit('INIT', res.DATA)
    else notice(res.MSG)
    return res
  },
  async registerEmail ({ commit }, data) {
    const res = await service.registerEmail(data)
    if (res.RET === 1) success(res.MSG)
    else notice(res.MSG)
    return res
  },
  async login ({ commit }, data) {
    const res = await service.login(data)
    if (data.memory) {
      window.localStorage.setItem('LOCALTOKEN', JSON.stringify(res.DATA))
    }
    if (res.RET === 1) commit('INIT', res.DATA)
    else notice(res.MSG)
    return res
  },
}

const mutations = {
  INIT (state, data) {
    state.token = data
    window.sessionStorage.setItem('TOKEN', JSON.stringify(data))
  },
  USER (state, data) {
    state.user = data
    window.sessionStorage.setItem('USER', JSON.stringify(data))
  },
  AROUNID (state, data) {
    state.user = data
    window.sessionStorage.setItem('AROUNID', JSON.stringify(data))
  },
  ROOMID (state, data) {
    state.user = data
    window.sessionStorage.setItem('ROOMID', JSON.stringify(data))
  }
}

export default new Vuex.Store({
  state,
  actions,
  mutations,
  modules: {
    details,
    jump
  }
})
